package custom.security.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * controller 日志打印切面
 * Created by security on 2017/9/24.
 */
@Slf4j
@Component
@Aspect
public class ControllerLogAspect {
    @Pointcut("execution(public * com.security.web.controller.*.*(..))")
    public void log(){}

    /**
     * 方法执行之前操作
     * @param joinPoint
     */
    @Before("log()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=sra.getRequest();
        //url
        log.info("url:{}",request.getRequestURL());

        //method
        log.info("method:{}" ,request.getMethod());

        //IP
        log.info("ip:{}",request.getRemoteAddr());

        //ClassMethod
        log.info("class_method:{}",joinPoint.getSignature().getDeclaringTypeName()
                +"."+joinPoint.getSignature().getName());

        //params
        log.info("params:{}",joinPoint.getArgs());
    }

    //在对象方法执行后行为
    @AfterReturning(returning = "object",value = "log()")
    public void after_GirlController(Object object){
        if(object!=null) {
            log.info("response:{}", object.toString());
        }
    }
}
